﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Reflection;
using System.IO;
using DevExpress.Web.ASPxUploadControl;
using EnterpriseFund.Common;
using DevExpress.Web.Mvc;

namespace EnterpriseFund.Controllers
{

    [OutputCache(Duration = 0, VaryByParam = "none")]   
    public class GSImportDateController : AdminBaseController
    {
        //
        // GET: /GSImportDate/
        /// <summary>
        /// 地税数据导入
        /// </summary>
        /// <returns>视图</returns>
        [AuthorityActionFilter("m_GSImportDate", Order = 1)]
        [LogPageActionFilter("国税数据导入", Order = 2)]
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GompareImportDateEdit(string nsrsbh,string bsrmc)
        {
            ViewData["NSRMC"] = bsrmc;
            ViewData["NSRSBH"] = nsrsbh;
            return View();
        }

        public string GompareImportDateSave(string nsrdzdah,string nsrsbh,string bsrmc,string xx)
        {
            try
            {
                if (xx != "" && xx.Split(',').Length == 3)
                {
                    xx = xx.Split(',')[2];
                }
                if (xx == "m099999")
                {
                    Model.DJ_OTHER_NSRXX dON = new Model.DJ_OTHER_NSRXX();
                    dON.FEntityNo = GlobalConstant.ENTITYNO;
                    dON.GS_NSRMC = bsrmc;
                    dON.GS_NSRSBH = nsrsbh;
                    dON.NSRDZDAH = decimal.Parse(nsrdzdah);
                    BLL.DJ_OTHER_NSRXX dONBLL = new BLL.DJ_OTHER_NSRXX();
                    dONBLL.Add(dON);

                    DataTable dt = System.Web.HttpContext.Current.Session["GSErrorData"] as DataTable;
                    DataRow[] drs = dt.Select(" NSRSBH='" + nsrsbh + "' AND NSRMC = '" + bsrmc + "' ");
                    foreach (DataRow dr in drs)
                    {
                        dr["NSRDZDAH"] = dON.NSRDZDAH;
                    }
                    OperateSession.del("GSErrorData");
                    System.Web.HttpContext.Current.Session["GSErrorData"] = dt;
                    System.Web.HttpContext.Current.Session.Timeout = 60 * 10;
                }
                else
                {
                    Model.DJ_NSRXX_Extension2 model = new Model.DJ_NSRXX_Extension2();
                    model.NSRDZDAH = decimal.Parse(nsrdzdah);
                    model.GS_NSRMC = bsrmc;
                    model.GS_NSRSBH = nsrsbh;
                    model.FEntityNo = GlobalConstant.ENTITYNO;
                    model.FInsDate = DateTime.Now;
                    model.FInsDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                    model.FInsEmpNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                    model.FInsIP = Common.GenerateUtil.GetClientIPv4Address();
                    model.FUpdDate = DateTime.Now;
                    model.FUpdDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                    model.FUpdEmplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                    model.FUpdIP = Common.GenerateUtil.GetClientIPv4Address();
                    BLL.DJ_NSRXX_Extension2 DJ_NSRXX_Extension2BLL = new BLL.DJ_NSRXX_Extension2();
                    Model.DJ_NSRXX_Extension2 model2 = DJ_NSRXX_Extension2BLL.GetModel(model.NSRDZDAH, GlobalConstant.ENTITYNO);
                    if (model2 != null)
                    {
                        DJ_NSRXX_Extension2BLL.Update(model);
                    }
                    else
                    {
                        DJ_NSRXX_Extension2BLL.Add(model);
                    }

                    DataTable dt = System.Web.HttpContext.Current.Session["GSErrorData"] as DataTable;
                    DataRow[] drs = dt.Select(" NSRSBH='" + nsrsbh + "' AND NSRMC = '" + bsrmc + "' ");
                    foreach (DataRow dr in drs)
                    {
                        dr["NSRDZDAH"] = model.NSRDZDAH;
                    }
                    OperateSession.del("GSErrorData");
                    System.Web.HttpContext.Current.Session["GSErrorData"] = dt;
                    System.Web.HttpContext.Current.Session.Timeout = 60 * 10;

                }
                return "ok";
            }
            catch
            {
                return "e";
            }
        }

        public ActionResult LargeDataComboBoxPartial()
        {
            return PartialView();
        }

        public ActionResult GompareImportDateListPartial()
        {
            DataTable dt = System.Web.HttpContext.Current.Session["GSErrorData"] as DataTable;
            DataRow[] drs = dt.Select(@" NSRDZDAH is null or 
                        (ZSXM_DM is null and ZSXM_MC is not null) or 
                        (SKZL_DM is null and SKZL_MC is not null) or 
                        (SKSX_DM is null and SKSX_MC is not null) or 
                        (SKCSFS_DM is null and SKCSFS_MC is not null) or 
                        (QLQQSLX_DM is null and QLQQSLX_MC is not null) or 
                        (TZLX_DM is null and TZLX_MC is not null) or 
                        (YZPZZL_DM is null  and YZPZZL_MC is not null) or 
                        (ZSPM_DM is null and ZSPM_MC is not null) or 
                        (JKPZZL_DM is null and JKPZZL_MC is not null) or 
                        (DJZCLX_DM is null and DJZCLX_MC is not null) or 
                        (HY_DM is null and HY_MC is not null) or 
                        (ZSFS_DM is null and ZSFS_MC is not null) or 
                        (YSKM_DM is null and YSKM_MC is not null) or 
                        (YSFPBL_DM is null and YSFPBL_MC is not null) or 
                        (SKGK_DM is null and SKGK_MC is not null)  ");
            if (drs.Count() == 0)
            {
                dt.Rows.Clear();
                return PartialView("GompareImportDateListPartial",dt);
            }
            drs = drs.OrderBy(s => s.Field<string>("nsrsbh")).ToArray();
            return PartialView("GompareImportDateListPartial", drs.CopyToDataTable());
        }

        public ActionResult GSImportDateListPartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string callbackArg = DevExpressHelper.CallbackArgument;

            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }

            string FYear = Request.Params["FYear"];
            string FPeriod = Request.Params["FPeriod"];
            string strwhere = "1=1";
            if (FYear != null && FYear != "")
            {
                strwhere += " and FYear='" + FYear + "'";
            }
            if (FPeriod != null && FPeriod != "")
            {
                strwhere += " and FPeriod='" + FPeriod + "'";
            }

            List<Model.GS_SB_ZSXX> GS_SB_ZSXXList = new List<Model.GS_SB_ZSXX>();
            GS_SB_ZSXXList = GetGS_SB_ZSXXList(strwhere, pageIndex);
            return PartialView("GSImportDateListPartial", GS_SB_ZSXXList);
        }

        /// <summary>
        /// 获取定义的工作时间数据
        /// </summary>
        /// <param name="strWhere">查询条件</param>
        /// <param name="pageIndex">第几页</param>
        /// <returns>查询出来的数据</returns>
        private List<Model.GS_SB_ZSXX> GetGS_SB_ZSXXList(string strWhere, int pageIndex)
        {
            BLL.Common commonBll = new BLL.Common();
            BLL.GS_SB_ZSXX GS_SB_ZSXXBLL = new BLL.GS_SB_ZSXX();
            string fiedls = "ZSXH";
            int total;
           // DataSet ds = commonBll.GetListByPage("fund.t_GS_SB_ZSXX", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, strWhere, "ZSXH", out total);
            DataSet ds = GS_SB_ZSXXBLL.GetList(strWhere);
            List<Model.GS_SB_ZSXX> GS_SB_ZSXXList = GS_SB_ZSXXBLL.DataTableToList(ds.Tables[0]);
            //List<Model.GS_SB_ZSXX> GS_SB_ZSXXAllList = new List<Model.GS_SB_ZSXX>();
            //total = GS_SB_ZSXXBLL.GetRecordCount(strWhere);
            //int pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            //for (int i = 0; i < total; i++)
            //{
            //    GS_SB_ZSXXAllList.Add(null);
            //}
            //for (int i = 0; i < pageRowSize; i++)
            //{
            //    if (GS_SB_ZSXXList.Count > i)
            //    {
            //        GS_SB_ZSXXAllList[((pageIndex - 1) * pageRowSize) + i] = GS_SB_ZSXXList[i];
            //    }
            //}

            return GS_SB_ZSXXList;
        }

        /// <summary>
        /// 删除页面
        /// </summary>
        /// <returns></returns>
        public ActionResult GSImportDateDelEdit()
        {
            return View();
        }
        /// <summary>
        /// 删除方法
        /// </summary>
        /// <returns></returns>
        public ActionResult GSImportDateDel()
        {
            string FYear = Fetch.Post("FYear");
            string FPeriod = Fetch.Post("FPeriod");

            try
            {
                BLL.GS_SB_ZSXX GS_SB_ZSXXBLL = new BLL.GS_SB_ZSXX();
                if (GS_SB_ZSXXBLL.ExistsTaxAuditDate(decimal.Parse(FYear), int.Parse(FPeriod)))
                {
                    ViewData["jsAlert"] = "您选择的批次已存在已审核数据，请作废后继续操作！";
                }
                else
                {
                    GS_SB_ZSXXBLL.Delete(decimal.Parse(FYear), int.Parse(FPeriod));
                    ViewData["jsAlert"] = "操作成功";
                }
            }
            catch
            {
                ViewData["jsAlert"] = "操作异常";
            }

            return View("GSImportDateDelEdit");
        }

        public ActionResult GSImportDateEdit()
        {
            OperateSession.del("GSErrorData");
            BLL.GS_SB_ZSXX GS_SB_ZSXXBLL = new BLL.GS_SB_ZSXX();
            ViewData["DQPC"] = GS_SB_ZSXXBLL.GetFPeriod();
            return View();
        }

        public string ExistsGSData(string fyear, string fPeriod)
        {
            BLL.GS_SB_ZSXX GS_SB_ZSXXBLL = new BLL.GS_SB_ZSXX();
            if (GS_SB_ZSXXBLL.Exists(decimal.Parse(fyear), int.Parse(fPeriod)))
            {
                return "Y";
            }
            else
            {
                return "N"; 
            }

        }


        public ActionResult GSImportDate()
        {
            try
            {
                string backname = string.Empty;
                string svrFileName = string.Empty;
                string uploadoffiepath = string.Empty;

                string saveUrl = string.Empty;

                UploadedFile[] uploadFiles = UploadControlExtension.GetUploadedFiles("upload");
                List<Model.GS_SB_ZSXX> SB_ZSXXList = new List<Model.GS_SB_ZSXX>();
                DataTable dt = new DataTable();
                // string isdel = Fetch.Post("delDate");
                string beginDate = Fetch.Post("BeginDate") + "-01";
                string endDate = Fetch.Post("EndDate") + "-01";
                string fYear = Fetch.Post("FYear");
                string fPeriod = Fetch.Post("FPeriod");

                int days = DateTime.DaysInMonth(DateTime.Parse(endDate).Year, DateTime.Parse(endDate).Month);
                endDate = Fetch.Post("EndDate") + "-" + days;

                if (null != uploadFiles && uploadFiles.Length > 0)
                {
                    for (int i = 0; i < uploadFiles.Length; i++)
                    {
                        UploadedFile upload = uploadFiles[i];
                        if (upload != null)
                        {
                            backname = upload.FileName.Substring(upload.FileName.LastIndexOf('.') + 1);
                            string entityNo = GlobalConstant.ENTITYNO;

                            string dest_dir = "/Publish/" + entityNo + "/GS_Date/" + DateTime.Now.Year + DateTime.Now.Month + "/";

                            string _oldfilename = upload.FileName.Substring(upload.FileName.LastIndexOf('\\') + 1);

                            svrFileName = "GS_DATA" + DateTime.Now.ToString("yyyyMMddHHmm") + "-" + _oldfilename;

                           
                            uploadoffiepath = Server.MapPath(Url.Content("~") + dest_dir);//上传文件的路径

                            if (!Directory.Exists(uploadoffiepath))//如果不存在就创建
                            {
                                Directory.CreateDirectory(uploadoffiepath);
                            }



                            upload.SaveAs(uploadoffiepath + svrFileName + "." + backname);
                            saveUrl = uploadoffiepath + svrFileName + "." + backname;
                        }
                    }
                }

                

                if (saveUrl == string.Empty)
                {
                    saveUrl = Fetch.Post("hidUrl");
                    beginDate = Fetch.Post("hidBeginDate");
                    endDate = Fetch.Post("hidEndDate");
                    fYear = Fetch.Post("hidFYear");
                    fPeriod = Fetch.Post("hidFPeriod");
                    svrFileName = Fetch.Post("hidsvrFileName"); 
                }

                BLL.SB_ZSXX SB_ZSXXBLL = new BLL.SB_ZSXX();
                DataSet ds = SB_ZSXXBLL.ReadExcelTitle(saveUrl);

                foreach (DataColumn dc in ds.Tables[0].Columns)
                {
                    dt.Columns.Add(dc.ColumnName);
                }

                foreach (DataColumn dc in ds.Tables[0].Columns)
                {
                    if (dc.ColumnName.Contains("_DM"))
                    {
                        dc.ColumnName = dc.ColumnName.Replace("_DM", "_MC");
                    }
                }

                Model.GS_SB_ZSXX GS_SB_ZSXXModel = new Model.GS_SB_ZSXX();
                PropertyInfo[] propertys = GS_SB_ZSXXModel.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    string tempName = pi.Name;
                    if (!dt.Columns.Contains(tempName))
                    {
                        dt.Columns.Add(tempName);
                        if (pi.PropertyType == typeof(DateTime?))
                        {
                            dt.Columns[tempName].DataType = typeof(DateTime);
                        }
                        else if (pi.PropertyType == typeof(decimal?))
                        {
                            dt.Columns[tempName].DataType = typeof(decimal);
                        }
                        else
                        {
                            dt.Columns[tempName].DataType = pi.PropertyType;
                        }
                    }
                    else
                    {
                        if (pi.PropertyType == typeof(DateTime?))
                        {
                            dt.Columns[tempName].DataType = typeof(DateTime);
                        }
                        else if (pi.PropertyType == typeof(decimal?))
                        {
                            dt.Columns[tempName].DataType = typeof(decimal);
                        }
                        else
                        {
                            dt.Columns[tempName].DataType = pi.PropertyType;
                        }
                    }
                }

                int z = 0;
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    DataRow dr2 = dt.NewRow();
                    foreach (DataColumn dc in dr.Table.Columns)
                    {
                        if (dt.Columns.Contains(dc.ColumnName))
                        {
                            try
                            {
                                if (dr[dc.ColumnName].ToString() != "")
                                {
                                    dr2[dc.ColumnName] = dr[dc.ColumnName];
                                }
                                else
                                {
                                    dr2[dc.ColumnName] = DBNull.Value;
                                }
                            }
                            catch
                            {
                                string aa = dc.ColumnName;
                            }

                        }

                    }
                    z++;
                    dr2["FExcelFileName"] = svrFileName;
                    dr2["FExcelRowNumber"] = z;
                    dr2["ZSXH"] = z;
                    dr2["FYear"] = fYear;
                    dr2["FPeriod"] = fPeriod;
                    dr2["FInsDeptNo"] = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                    dr2["FInsDate"] = DateTime.Now;
                    dr2["FInsIP"] = Common.GenerateUtil.GetClientIPv4Address();
                    dr2["FInsEmpNo"] = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                    dr2["FEntityNo"] = Common.GlobalConstant.ENTITYNO;
                    dt.Rows.Add(dr2);
                }

                string type = Fetch.Post("hidtype");
                if (type != "Y")
                {

                    var query2 = (from nm in dt.AsEnumerable() where nm.Field<DateTime?>("RKRQ") == null  select nm);
                    if (query2.Count() == 0)
                    {
                        var query = (from nm in dt.AsEnumerable() where  (nm.Field<DateTime>("RKRQ") - DateTime.Parse(endDate)).Days <= 0 && (nm.Field<DateTime>("RKRQ") - DateTime.Parse(beginDate)).Days >= 0 select nm);

                        if (query.Count() > 0)
                        {
                            if (query.Count() == dt.Rows.Count)
                            {
                                BLL.GS_SB_ZSXX GS_SB_ZSXXBLL = new BLL.GS_SB_ZSXX();
                                Model.GSGompareDate gmodel = GS_SB_ZSXXBLL.GompareImportDate(dt);
                                if (gmodel.ErrorData != null)
                                {
                                    ViewData["jsAlert"] = gmodel.Message;
                                    ViewData["fYear"] = fYear;
                                    ViewData["fPeriod"] = fPeriod;
                                    ViewData["type"] = "N";
                                    ViewData["data"] = gmodel.ErrorData;
                                    System.Web.HttpContext.Current.Session["GSErrorData"] = gmodel.ErrorData;
                                    System.Web.HttpContext.Current.Session.Timeout = 60 * 10;

                                    ViewData["svrFileName"] = svrFileName;
                                }
                                else
                                {
                                    ViewData["jsAlert"] = gmodel.Message;
                                    ViewData["fYear"] = fYear;
                                    ViewData["fPeriod"] = fPeriod;
                                    ViewData["type"] = "N";
                                }
                                //ViewData["jsAlert"] = GS_SB_ZSXXBLL.GompareImportDate(dt);
                                //ViewData["type"] = "N";
                            }
                            else
                            {
                                ViewData["jsAlert"] = "文件中存在不在指定时间内的数据，是否继续导入？";
                                ViewData["Url"] = saveUrl;
                                ViewData["beginDate"] = beginDate;
                                ViewData["endDate"] = endDate;
                                ViewData["fYear"] = fYear;
                                ViewData["fPeriod"] = fPeriod;
                                ViewData["type"] = "Y";
                                ViewData["svrFileName"] = svrFileName;
                            }
                        }
                        else
                        {
                            ViewData["jsAlert"] = "未在文件中找到指定时间内的数据，是否继续导入？";
                            ViewData["Url"] = saveUrl;
                            ViewData["beginDate"] = beginDate;
                            ViewData["endDate"] = endDate;
                            ViewData["fYear"] = fYear;
                            ViewData["fPeriod"] = fPeriod;
                            ViewData["type"] = "Y";
                            ViewData["svrFileName"] = svrFileName;

                        }
                    }
                    else
                    {
                        ViewData["jsAlert"] = "入库时间不可为空请修改后重新导入";
                        ViewData["Url"] = saveUrl;
                        ViewData["beginDate"] = beginDate;
                        ViewData["endDate"] = endDate;
                        ViewData["fYear"] = fYear;
                        ViewData["fPeriod"] = fPeriod;
                        ViewData["type"] = "N";
                        ViewData["svrFileName"] = svrFileName; 
                    }
                }
                else
                {
                    BLL.GS_SB_ZSXX GS_SB_ZSXXBLL = new BLL.GS_SB_ZSXX();
                    Model.GSGompareDate gmodel = GS_SB_ZSXXBLL.GompareImportDate(dt);
                    if (gmodel.ErrorData != null)
                    {
                        ViewData["jsAlert"] = gmodel.Message;
                        ViewData["fYear"] = fYear;
                        ViewData["fPeriod"] = fPeriod;
                        ViewData["type"] = "N";
                        ViewData["data"] = gmodel.ErrorData;
                        System.Web.HttpContext.Current.Session["GSErrorData"] = gmodel.ErrorData;
                        System.Web.HttpContext.Current.Session.Timeout = 60 * 10;

                        ViewData["svrFileName"] = svrFileName;
                    }
                    else
                    {
                        ViewData["jsAlert"] = gmodel.Message;
                        ViewData["fYear"] = fYear;
                        ViewData["fPeriod"] = fPeriod;
                        ViewData["type"] = "N";
                    }
                }

                //if (query.Count() > 0)
                //
              
                //string strwhere = "";
                //if (isdel == "C")
                //{
                //    isdel = "Y";
                //    strwhere = " DATEDIFF(DAY,'" + beginDate + "',RKRQ)>=0 and DATEDIFF(DAY,'" + endDate + "',RKRQ)<=0 ";
                //}
                //}
                //else
                //{
                //    ViewData["jsAlert"] = "未在文件中找到指定时间内的数据，请核对后重新导入";
                //}
                BLL.GS_SB_ZSXX GS_SB_ZSXXBLL2 = new BLL.GS_SB_ZSXX();
                ViewData["DQPC"] = GS_SB_ZSXXBLL2.GetFPeriod();
                return View("GSImportDateEdit");
            }
            catch(Exception ex)
            {
                ViewData["jsAlert"] = ex.Message;
                ViewData["type"] = "N";
                BLL.GS_SB_ZSXX GS_SB_ZSXXBLL2 = new BLL.GS_SB_ZSXX();
                ViewData["DQPC"] = GS_SB_ZSXXBLL2.GetFPeriod();
                return View("GSImportDateEdit");
            }
        }

    }
}
